<?php
// NOTE: The methods defined in this file has been inspired from the file lock module:
//     https://drupal.org/project/file_lock

// Arbitrary id; Modules have no id, but file_usage want's one.
define("MEDIA_FILE_DELETE_ID", 3183);
define("MEDIA_FILE_DELETE_NAME", 'media_file_delete');

function media_file_delete_lock_file($file) {
  if (!media_file_delete_is_locked($file)) {
    // Only add one lock for every file.
    // https://api.drupal.org/api/drupal/includes%21file.inc/function/file_usage_add/7
    file_usage_add($file, MEDIA_FILE_DELETE_NAME, 'module', MEDIA_FILE_DELETE_ID);
  }
}

function media_file_delete_unlock_file($file) {
  if (media_file_delete_is_locked($file)) {
    file_usage_delete($file, MEDIA_FILE_DELETE_NAME, MEDIA_FILE_DELETE_ID);
  }
}

// Unlock all file after uninstall
function media_file_delete_unlock_all_file() {
  // According to the API, FALSE load all files:
  //     https://api.drupal.org/api/drupal/includes%21file.inc/function/file_load_multiple/7
  //     https://api.drupal.org/api/drupal/includes%21common.inc/function/entity_load/7
  $files = file_load_multiple(FALSE);
  foreach ($files as $file) {
    media_file_delete_unlock_file($file);
  }
}

// Lock all file after install
function media_file_delete_lock_all_file() {
  $files = file_load_multiple(FALSE);
  foreach ($files as $file) {
    media_file_delete_lock_file($file);
  }
}

/**
 * Check if a file has already an entry in file_usage for media_file_delete
 *
 * @param file $file
 *   the file to check
 *
 * @return bool
 *   TRUE if file is locked by this module
 *   FALSE if file is not locked by this module
 */
function media_file_delete_is_locked($file) {
  $file_usage_list = file_usage_list($file);
  return isset($file_usage_list[MEDIA_FILE_DELETE_NAME]);
}

?>
